import 'dart:async';
import 'dart:convert';

import 'package:flutter_animate/flutter_animate.dart';
import 'package:get/get.dart';
import 'package:series_play/utils/log.dart';

/// 分页列表控制器
abstract class BaseListController<T> extends GetxController {
  int _page = 1;
  int _pageSize = 20;

  RxBool isEmptyData = false.obs;
  RxBool isNoMoreData = false.obs;
  RxList<T> dataList = <T>[].obs;
  RxBool isRefreshing = true.obs;
  RxBool isLoading = false.obs;

  Future<List<T>> onLoad(int page, int pageSize, bool isRefresh);

  setPageSize(int pageSize) {
    _pageSize = pageSize;
  }

  void setData(List<T> list) {
    dataList.value = list;
    isEmptyData.value = list.isEmpty;
  }

  void addData(List<T> list) {
    dataList.addAll(list);
  }

  FutureOr<dynamic>? onRefresh() async {
    try {
      _page = 1;
      isNoMoreData.value = false;
      isLoading.value = false;
      isRefreshing.value = true;
      isEmptyData.value = false;
      var list = await onLoad(_page, _pageSize, true);
      isRefreshing.value = false;
      setData(list);
    } catch (e) {
      isRefreshing.value = false;
      Log.w('onRefresh处理异常:${json.encode(e)}');
    }
  }

  FutureOr<dynamic>? onLoadMore() async {
    try {
      _page++;
      isLoading.value = true;
      isRefreshing.value = false;
      Future.delayed(2000.ms , () async{
        var list = await onLoad(_page, _pageSize, false);
        isLoading.value = false;
        addData(list);
        isNoMoreData.value = list.length < _pageSize;
      });
    } catch (e) {
      isLoading.value = false;
      Log.w('onLoadMore处理异常:${json.encode(e)}');
    }
  }

  Future<void> onRefreshing() async {
    await onRefresh();
  }

  Future<void> onLoadingMore() async {
    await onLoadMore();
  }

  @override
  void onClose() {
    super.onClose();
    dataList.close();
  }

}